package org.cug.controller;

import io.swagger.v3.oas.annotations.Operation;
import org.cug.pojo.Result;
import org.cug.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Author: gongshihao
 * @Date: 2024-05-17-10:57
 * @Description: this is my code
 */
@RestController
@RequestMapping
public class FileUploadController {
    /**
     * 图像上传
     * @author gongshihao
     * @param file
     * @return
     * @State 已测验
     */
    @Operation(summary = "上传图片", description = "通过multipart/form-data上传图片")
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public Result<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
            String originalFilename = file.getOriginalFilename();
            // 保证文件的名字都不相同,使用UUID进行拼接
            String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 保存文件到服务器或云存储
            String url = AliOssUtil.uploadFile(filename, file.getInputStream());
            return Result.success(url);
        }
    }
